#include "usart.h"
#include "uart_to_soc.h"
#include "stdio.h"
#include "upgrade.h"
#include "log.h"

void soc_uart_cmd_handler(void)
{
    uint16_t len = 0;
    uint8_t ack = 0xCC;
    
    if (start_transfer_flag == 1)
    {
        send_log_to_soc();
        return ;
    }
    
    if (UART_RX_DMA_Status() & UART_RX_STAT_MASK) //receive data
    {
        len = UART_RX_DMA_Status() & ~UART_RX_STAT_MASK;
        
        if( len > 600 || len < 4 ) // receive data length is not legal
        {
            UART_RX_DMA_Status_Clear();
            UART_RX_DMA_Enable();  //enable next dma data receive.
            return ; 
        }
       
        if ((UART_RX_BUF[0] & 0xE0) == 0xE0) //command 
        {
            switch(UART_RX_BUF[0])
            {
                case SOC_UART_CMD_UPGRADE: //upgrade command
                    if ( get_upgrade_status() != MCU_START_UPGRADE_STATUS )  //get upgrade status
                    {
                        mcu_begin_upgrade();  //begin upgrade. erase flash 
                        ack = MCU_EXCUTE_CMD_SUCCESS;
                    }
                    else
                    {
                        ack = MCU_UPGRADE_IN_PROCESS;
                    }
                    break;
                
                case SOC_UART_CMD_REBOOT:   //reset command
                    //do_mcu_reset();
                    ack = MCU_EXCUTE_CMD_SUCCESS;
                    break;
                
                case SOC_UART_CMD_CONFIGURE:
                    ack = MCU_EXCUTE_CMD_SUCCESS;
                    break;
                
                case SOC_UART_CMD_GET_LOG:
                    begin_send_log();
                    ack = MCU_EXCUTE_CMD_SUCCESS;
                    break;
                
                default: 
                    ack = MCU_CMD_UNDEFINED;
                    break;
            }
        }
        else // upgrade data 
        {
            if( get_upgrade_status() ==  MCU_START_UPGRADE_STATUS) //get upgrade status
            {
               ack = mcu_upgrade_packet(UART_RX_BUF, len);
            }
        }
        
        Serial_PutByte(ack); //send ack to lite soc
        
        UART_RX_DMA_Status_Clear(); //clear data flag
        UART_RX_DMA_Enable();  //enable next dma date transfer
    }
}

